import {
  getDocumentSummary,
  getKnowledgeStatusById,
  uploadDocumentByUrl,
  uploadDocumentByFile,
  getDocumentSuggestion
} from '@/api/chat'
import store from '@/store'
import PsMessage from '@/components/message/index'
import PsMessageBox from '@/components/message-box/index'
import { createReadCharFunc } from '@/utils/stream-reader-markdown'
import { invokeAPi } from '@/xz-fn.js'
import { encode } from 'js-base64'
import { pick } from 'lodash-es'
import { awaitNextick } from '@/utils/index'

// import { report } from '@/directives/report'
// import { getVisibleHtml } from '@/utils/index'

export default function createDocFunc () {
  // 检测登录
  const detectIsLogin = () => {
    if (store.getters.hasLogin) return true
    PsMessage({ message: '请您登录后再使用' })
    setTimeout(() => {
      this.$gotoLogin()
    }, 1000)
    return false
  }
  function detechRestRights (type) {
    if (process.env.VUE_APP_BUY_TYPE === 'right') {
      const usedModel = getUsedModel(type)
      const { right_id } = usedModel
      if (!right_id) return true
      const rights = store.getters.userInfo.userRights
      const rest = rights.find((v) => v.right_id === right_id)?.rest_limit
      if (rest === 0) {
        toastError(1008)
        return false
      }
    } else if (process.env.VUE_APP_BUY_TYPE === 'token') {
      const rest = store.getters.userInfo.userToken
      const minCount = process.env.VUE_APP_MIN_COUNT
      if (rest < minCount) {
        toastError(1008)
        return false
      }
    }

    return true
  }
  // async function hasLimitByRight (right_id) {
  //   // if (store.getters.userInfo.restTokens > 0) return [false, false, 0]
  //   if (store.getters.userInfo.userRights.length > 0) {
  //     const right = store.getters.userInfo.userRights.find((v) => v.right_id === right_id) || ({})
  //     return [right?.rest_limit === 0, right.is_vip, right.total]
  //   }
  //   await store.dispatch('user/getUserRights')
  //   const right = store.getters.userInfo.userRights.find((v) => v.right_id === right_id) || ({})
  //   return [right?.rest_limit === 0, !!right.is_vip, right.total || 0]
  // }

  // eslint-disable-next-line sonarjs/cognitive-complexity
  function toastError (code, type, msg) {
    updateUserToken()// 修复停止对话的时候，次数没更新问题
    if (code === 4003) {
      if (process.env.VUE_APP_BUY_TYPE === 'energy') {
        if (!store.getters.userInfo.is_member) {
          invokeAPi('HtmlClickReport', { ReportID: 7702 })
          // eslint-disable-next-line sonarjs/no-duplicate-string
          store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，升级会员/购买加量包释放全能生产力吧！', eid: 8502 })
          // eslint-disable-next-line sonarjs/no-duplicate-string
          type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
          return true
        }
        invokeAPi('HtmlClickReport', { ReportID: 7706 })
        store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，购买能量包释放全能生产力吧！<span class="vip-color">会员优享购买折扣哦！</span>' })
        type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
        return true
      }
      invokeAPi('HtmlClickReport', { ReportID: 7702 })
      // eslint-disable-next-line
        store.dispatch('system/setVipGuide', { status: true, title: msg || `您的阅读&文档总结次数已达到免费上限，升级VIP享AI特权，高效助力办公浏览查询！`, eid: 8502 })
      // eslint-disable-next-line sonarjs/no-duplicate-string
      type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
      return true
    }
    if (code === 4002 && process.env.VUE_APP_BUY_TYPE === 'right') {
      invokeAPi('HtmlClickReport', { ReportID: 7706 })
      PsMessageBox(
        {
          message: `尊敬的VIP，您本月该功能权益次数已用完，您可以于次月购买日起再使用`,
          title: '权益提示',
          confirmButtonText: '知道了',
          showCancelButton: false,
          width: 312,
          confirmButtonClass: 'btn__primary_vip',
          beforeClose: (action, instance, done) => {
            done()
          }
        }
      )
      type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
      return true
    }
    if (code === 1008) {
      if (process.env.VUE_APP_BUY_TYPE === 'token') {
        // eslint-disable-next-line
        store.dispatch('system/setVipGuide', { status: true, title: '您的token余额不足，补充token释放全能生产力吧！' })
        return
      }
      if (process.env.VUE_APP_BUY_TYPE === 'energy') {
        if (!store.getters.userInfo.is_member) {
          invokeAPi('HtmlClickReport', { ReportID: 7702 })
          store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，升级会员/购买加量包释放全能生产力吧！', eid: 8502 })
          type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
          return true
        }
        invokeAPi('HtmlClickReport', { ReportID: 7706 })
        store.dispatch('system/setVipGuide', { status: true, title: '您的AI能量不足，购买能量包释放全能生产力吧！<span class="vip-color">会员优享购买折扣哦！</span>' })
        type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
        return true
      }
      if (!store.getters.userInfo.is_member) {
        invokeAPi('HtmlClickReport', { ReportID: 7702 })
        store.dispatch('system/setVipGuide', { status: true, title: '您的权益余额不足，升级会员释放全能生产力吧！', eid: 8502 })
        type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
        return true
      }
      invokeAPi('HtmlClickReport', { ReportID: 7706 })
      PsMessageBox(
        {
          message: `尊敬的VIP，您本月该功能权益次数已用完，您可以于次月购买日起再使用`,
          title: '权益提示',
          confirmButtonText: '知道了',
          showCancelButton: false,
          width: 312,
          confirmButtonClass: 'btn__primary_vip',
          // eslint-disable-next-line sonarjs/no-identical-functions
          beforeClose: (action, instance, done) => {
            done()
          }
        }
      )
      type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code })
      return true
    }
    if (code === 1009) {
      // eslint-disable-next-line sonarjs/no-duplicate-string
      type && store.dispatch('chat/setDocumentSummarize', { status: 'error', type, data: undefined, code, errMsg: msg })
      return true
    }
    return false
  }

  const readChar = createReadCharFunc('summary')

  // 轮询文档状态
  function pollingDocumentStatus (document_id) {
    let retryTimes = 10
    return new Promise((resolve) => {
      let timerId = null
      const pollingRequest = () => {
        getKnowledgeStatusById(document_id)
          .then(({ data }) => {
            if (data?.data?.status === 'finished') {
              if (timerId) clearTimeout(timerId)
              resolve({ status: data?.data?.status })
              return
            }
            if (retryTimes <= 0) {
              resolve({ timeout: true })
              return
            }
            retryTimes--
            timerId = setTimeout(pollingRequest, 4000)
          })
          .catch((err) => {
            resolve({ err })
          })
      }
      pollingRequest()
    })
  }

  // 渲染文档总结
  async function renderSummarize (summary) {
    store.dispatch('chat/setDocumentSummarize', { status: 'chating', data: { summary: '' } })
    await readChar(store.getters.chatStore.docSummarize.document, summary)
    store.dispatch('chat/setDocumentSummarize', { status: 'end' })
    await awaitNextick(0.1)
    await getDocQuestions()
    await updateUserToken()
    if (store.getters.userInfo.userToken < process.env.VUE_APP_MIN_COUNT) {
      toastError(1008)
    }
  }

  // 获取推荐问题
  async function getDocQuestions () {
    const knowledge_id = store.getters.chatStore.docSummarize.document.knowledge_id
    // console.log('store.getters.chatStore.docSummarize.document.knowledge_id', store.getters.chatStore.docSummarize.document.knowledge_id)
    const { data } = await getDocumentSuggestion(knowledge_id)
    // eslint-disable-next-line sonarjs/no-duplicate-string
    store.dispatch('chat/setDocSummarize', { questions: data?.data.suggested_questions || [] })
  }

  // 更新上传进度
  function processEvent (e) {
    if (e.type === 'progress') {
      store.dispatch('chat/setDocSummarize', { process: (e.loaded / e.total) * 100 })
    }
  }

  function getUsedModel (type) {
    const cur = store.getters.chatStore.currentDocumentModel
    const models = store.getters.chatStore.documentModels
    if (type === 'link') {
      if (cur?.supported_file_type?.includes('TEXT')) return cur
      return models.find((v) => v.supported_file_type.includes('TEXT')) || ({})
    }
    if (type === 'pdf') {
      if (cur?.supported_file_type?.includes('PDF')) return cur
      return models.find((v) => v.supported_file_type.includes('PDF')) || ({})
    }
    return cur
  }

  // 上传文档
  function uploadDocument (type, doc, model) {
    if (type === 'link') {
      const data = doc
      return uploadDocumentByUrl(data.url, data.title, encode(data.content), model.model)
    }
    const data = doc
    return uploadDocumentByFile(data.file, model.model, data.title, processEvent)
  }

  // 开始文档对话
  // eslint-disable-next-line sonarjs/cognitive-complexity
  async function startChatDocument (type, data) {
    let docItem = {}
    docItem = { ...data }
    store.dispatch('chat/reset')
    store.dispatch('chat/setDocumentSummarize', { status: 'upload', type, data: docItem })
    // eslint-disable-next-line sonarjs/no-duplicate-string
    store.dispatch('chat/setChatStore', { isChating: true })
    await awaitNextick(0.3)
    const useModel = getUsedModel(type)
    store.dispatch('chat/setDocSummarize', { documentModel: useModel.model || '', documentModelName: store.getters.chatStore.currentDocumentModel.name || '' })
    const { data: doc } = await uploadDocument(type, docItem, useModel)
    await awaitNextick(0.2)
    store.dispatch('chat/setCurrentModel', { model: useModel, type: 'doc' })
    if (toastError(doc?.code, type, doc?.msg)) return
    if (doc?.code !== 200) {
      // eslint-disable-next-line sonarjs/no-duplicate-string
      PsMessage({ message: doc?.msg || '文档上传错误，请稍后再试' })
      store.dispatch('chat/setDocumentSummarize', { status: 'error' })
      return null
    }

    if (doc.data.summary) {
      store.dispatch('chat/setDocumentSummarize', { status: 'chating',
        type,
        data: {
          ...pick(doc.data, ['document_id', 'knowledge_id'])
        }
      })

      if (doc.data.conversation_id) store.dispatch('chat/setChatStore', { conversionId: doc.data.conversation_id })

      await renderSummarize(doc.data.summary)
      return doc?.data
    }

    const { document_id, knowledge_id } = doc.data
    store.dispatch('chat/setDocumentSummarize', { status: 'analysis', type })
    const { status } = await pollingDocumentStatus(document_id)

    if (status !== 'finished') {
      store.dispatch('chat/setDocumentSummarize', { status: 'error' })
      PsMessage({ message: '文档上传错误，请稍后再试' })
      return
    }
    // report(121)

    const { data: docData } = await getDocumentSummary(knowledge_id, document_id)
    if (toastError(docData?.code, type)) return
    if (docData?.code === 1012) {
      PsMessageBox({
        message: `当前选择的文档大小超过当前模型允许范围`,
        title: '提示',
        confirmButtonText: '切换高级模型',
        cancelButtonText: '重新选择文档',
        width: 312,
        beforeClose: (action, instance, done) => {
          if (action === 'cancel') {
            handlePdfSummrize()
          }
          done()
        }
      })
      store.dispatch('chat/setDocumentSummarize', { status: 'error', type: 'pdf', data: undefined, code: docData.code })
      return
    }
    if ([1013, 1028].includes(docData?.code)) {
      PsMessageBox({
        message: `当前模型为VIP专享，马上开通享更多特权吧！`,
        title: '权益提示',
        confirmButtonText: '开通VIP',
        cancelButtonText: '知道了',
        width: 312,
        // eslint-disable-next-line sonarjs/no-identical-functions
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$gotoMember()
            // report(242, type)
          }
          done()
        }
      })
      store.dispatch('chat/setDocumentSummarize', { status: 'error', type: 'pdf', data: undefined, code: docData.code })
      return
    }
    if (docData?.code !== 200) {
      PsMessage({ message: '文档上传错误，请稍后再试' })
      store.dispatch('chat/setDocumentSummarize', { status: 'error' })
      return
    }

    store.dispatch('chat/setDocumentSummarize', { status: 'chating',
      type,
      data: {
        ...pick(docData.data, ['document_id', 'knowledge_id'])
      }
    })
    if (docData.data.conversation_id) store.dispatch('chat/setChatStore', { conversionId: docData.data.conversation_id })
    await renderSummarize(docData?.data?.summary)
    return docData?.data
  }

  // 网页总结
  // async function handleWebPageSummarize () {
  //   if (!detectIsLogin()) return
  //   if (store.getters.chatStore.docSummarize.status === 'upload') {
  //     PsMessage({ message: '文件正在上传中，请稍后' })
  //     return
  //   }
  //   if (store.getters.chatStore.docSummarize.status === 'analysis') {
  //     PsMessage({ message: '正在总结中，请稍后' })

  //     return
  //   }
  //   const url = location.href
  //   const title = document.title
  //   const content = getVisibleHtml()
  //   if (
  //     store.getters.chatStore.docSummarize.document.url === url &&
  //     store.getters.chatStore.docSummarize.status !== 'error' &&
  //     store.getters.chatStore.docSummarize.documentModel === store.getters.chatStore.currentDocumentModel.model
  //   ) {
  //     PsMessage({ message: '当前页面已总结，无需重复总结' })
  //     return
  //   }
  //   const [limit, is_vip] = await hasLimitByRight('80210')
  //   if (limit) {
  //     if (is_vip) {
  //       toastError(
  //         4002,
  //         undefined,
  //         '尊敬的VIP，您本月阅读&文档总结权益次数已用完，请于次月购买日（含）起再使用'
  //       )
  //       return
  //     }
  //     toastError(
  //       4003,
  //       undefined,
  //       `您的网页总结次数已达到免费上限，升级VIP享AI特权，高效助力办公浏览查询！`
  //     )
  //     return
  //   }

  //   await startChatDocument('link', { url, title, content })
  // }

  async function handlePdfSummrize (file) {
    if (!detectIsLogin()) return
    if (store.getters.chatStore.docSummarize.status === 'upload') {
      PsMessage({ message: '文件正在上传中，请稍后' })
      return
    }
    if (store.getters.chatStore.docSummarize.status === 'analysis') {
      PsMessage({ message: '正在分析中，请稍后' })
      return
    }
    if (store.getters.chatStore.docSummarize.status === 'chating') {
      PsMessage({ message: '文档正在总结中, 请稍后' })
      return
    }
    store.dispatch('chat/reset')
    store.dispatch('chat/resetDocumentSummarize', {})
    store.dispatch('chat/setChatStore', { isChating: true })
    if (file) {
      await startChatDocument('pdf', { file, title: file.name })
      window.__tmp_xz_chat_pdf_file__ = file
      return
    }
    store.dispatch('chat/setDocumentSummarize', { status: 'wait', type: 'pdf' })
  }
  function updateUserToken () {
    invokeAPi('BroadcastData', 'aichat:onAiTokenChange')
    return store.dispatch('user/getUserRights', true)
  }
  return {
    // handleWebPageSummarize,
    detechRestRights,
    startChatDocument,
    handlePdfSummrize
  }
}
